## -*- coding: utf-8 -*-
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>我看图 &gt;&gt; ${album.name}</title>
        <link href="/assets/default.css" rel="stylesheet" type="text/css" />
        <style type="text/css">
            body { background: #333; }
            #main_photo { margin: 0 auto; display: block; }
            #index_tip { position: absolute; left: 0; top: 0; color: #ddd; font: bold 30px Georgia, 'Palatino Linotype', serif; z-index: 100; display: none; }
                #num_of_photos { font-size: 20px;  }
            #func_bar { position: absolute; left: 0; bottom: 0; width: 100%; overflow: hidden; display: none; }
            #func_bar, #toolbar { position: absolute; left: 0; }
            #toolbar { height: 100%; width: 20px; top: 0; }
                #toolbar a { display: block; margin: 15px 5px; height: 16px; width: 16px; opacity: 0.8; transition: all 130ms ease 0s; }
                #toolbar a:hover { opacity: 1; }
                    #nav_close { background: url("/assets/lightbox.png") no-repeat scroll -13px -111px transparent; }
                    #nav_back, #nav_back_2 { background: url("/assets/lightbox.png") no-repeat scroll 0 0 transparent; }
            #thumb_container { overflow: hidden; position: relative; left: 26px; } /*100 是 toolbar 的宽度*/
            #func_bar ul { position: relative; }
            #func_bar li { display: inline; }
                /*.highlightedThumb { padding: 0 4px; }*/
                .highlightedThumb { border: 3px solid #fff; }
                
                #bottom_panel { position: absolute; bottom: 0; z-index: 100; width: 100%; }
                    #nav_zone { margin: 0 auto; width: 108px; }
                    #bottom_panel a, #nav_back_2 { display: block; float: left; margin: 5px 8px; height: 20px; width: 20px; opacity: 0.8; transition: all 130ms ease 0s; }
                    #bottom_panel a:hover { opacity: 1; }
                    #footer_left, #footer_right{ position: absolute; top: 0; line-height: 30px; vertical-align: middle; font: 14px 'Palatino Linotype', serif; color: #fff; padding: 5px; }
                    #footer_left { left: 36px; }
                    #footer_right { right: 0; }
                /*icons from Google+*/
                    #nav_button { background: url("/assets/lightbox.png") no-repeat scroll -106px -95px transparent; }
                    #nav_prev_p { background: url("/assets/lightbox.png") no-repeat scroll 0 -58px transparent; }
                    #nav_next_p { background: url("/assets/lightbox.png") no-repeat scroll -250px -127px transparent; }
            #desc { position: absolute; background: rgba(0,0,0,0.5); padding-left: 10px; border-left: 5px solid #ccc; font-size: 16px; color: #fff; text-align: left; }
            #loading { position: absolute; left: 50%; top: 50%; margin-left: -25px; margin-top: -25px; text-align: center; z-index: 50; }
        </style>
        <script type="text/javascript" src="/assets/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
            var ids = ${ids};
            var urls = ${urls};
            //preloadStatus 数组代表对应的图片是否已被预读。1：已读；0：未读
            var preloadStatus = new Array(urls.length);
            //oriDimension 数组记录照片的原始长宽
            var oriDimension = ${dimensions};
            //一次预读张数，默认是 5
            var BATCH_LOAD_LIMIT = 8;
            var thumb_loaded = false;
            for(var i = 0; i < urls.length; i++){
                preloadStatus[i] = 0;
            }
            
            var photoInfo = ${info};
            var currentId;
            
            var DEBUG_SWITCH = true;
            function _debug(str){
                if(window.console && DEBUG_SWITCH){
                    console.info(str);
                }
            }
            
            //从 index+1 开始预读
            function preloadImg(index, count){
                //_debug('Enter preload: ' + index + ', ' + count + ', ' + $("body").data("shouldPreload"));
                if($("body").data("shouldPreload") == true){
                    var idx  = (index + 1) % urls.length;
                    do{
                        if(preloadStatus[idx] == 0){
                            break;
                        }else{
                            idx = ++idx % urls.length;
                            count--;
                        }
                    }while(idx != index || count == 0)
                    
                    if(idx == index){
                        //已经全部预读取，退出
                        $("body").data("allPreloaded", true);
                    }else if(count > 0){
                        var tmpImg = new Image();
                        tmpImg.src = urls[idx]; 
                        $(tmpImg).load(function(){
                            _debug('Preloaded(' + (BATCH_LOAD_LIMIT - count + 1) + '): ' + idx);
                            preloadStatus[idx] = 1;
                            /*
                            var _w = $(this).width(), _h = $(this).height();
                            if(!oriDimension[idx]){
                                oriDimension[idx] = [_w, _h];
                            }
                            _debug(oriDimension);
                            */
                            //_debug("INDEX: " + idx + " LOADED");
                            $("body").data("preloadCount", $("body").data("preloadCount") + 1);
                            preloadImg(idx, count - 1);
                        });
                    }
                }
            }
            
            function switchToPhoto(index){
                _debug('Switch to: ' + index);
                currentId = ids[index];
                $('#loading').show();
                var url = urls[index];
                
                //打断正在预读的图片队列
                $("body").data("shouldPreload", false);
                //$('#main_photo').width('').height('');
                $('#main_photo').attr('src', url);
                reposition();
                updatePhotoInfo();
                $('#main_photo').load(function(index){
                    _debug('Loaded: ' + index);
                    preloadStatus[index] = 1;
                    if($("body").data("allPreloaded" == false)){
                        $("body").data("shouldPreload", true);
                        preloadImg(index, BATCH_LOAD_LIMIT);
                    }
                    /*
                    var _w = $(img).width(), _h = $(img).height();
                    if(!oriDimension[index]){
                        oriDimension[index] = [_w, _h];
                    }
                    _debug(oriDimension);
                    */
                        /*
                    if(id + '' in photoInfo){
                        updatePhotoInfo(id);
                    }else{
                        $.get('/photo/info/' + id, null, function(data){
                            updatePhotoInfo(id, data);
                            photoInfo[id] = data;
                        }, "json");
                    }
                        */
                }(index));
            }
            
            function reposition(){
                var index = $.inArray(currentId, ids);
                var imgObj = $('#main_photo');
                var _w = oriDimension[index][0], _h = oriDimension[index][1], _r = _w / _h;
                var _ww = $(window).width(), _wh = $(window).height();
                var _eh;    //extra height
                
                if($('#bottom_panel').is(':hidden')){
                    _eh = 113;  //$('#func_bar').height();
                }else{
                    _eh = $('#bottom_panel').height();
                }
                _wh -= _eh;
                var _wr = _ww / _wh;
                
                var _tw = _w, _th = _h;
                if(_w > _ww && _r >= _wr){
                    //_tw = _ww - $('#index_tip').width() - 20;
                    _tw = _ww;
                    _th = _tw / _r;
                }else if(_h > _wh && _r <= _wr){
                    //_th = _wh - $('#index_tip').width() - 20;
                    _th = _wh;
                    _tw = _th * _r;
                }
                imgObj.width(_tw).height(_th).css('margin-top', (_wh - _th) / 2 + 'px');
                $('#desc').css({
                    'width': _tw - 15 + 'px', //FIXME: hard-coding. leftpadding: 10, leftborder:5
                    'left': (_ww - _tw) / 2 + 'px',
                    'bottom': (_wh - _th)/ 2 + _eh + 'px'
                });

                //$('#bottom_panel').css('left', (_ww - $('#bottom_panel').width()) / 2 + 'px');
                //_debug('Window    : ' + _ww + ', ' + _wh);
                //_debug('Resized to: ' + _tw + ', ' + _th);
            }
            
            function updatePhotoInfo(){
                //photo.name, photo.desc, photo.time_created
                var id = currentId;
                var index = $.inArray(id, ids)
                var info = photoInfo[id + ''];
                $('#footer_left').text(index + 1 + ' / ' + ids.length);
                $('#footer_right').text(info['capTime']);
                $('#main_photo').attr('alt', info['name']);
                $('#desc').text(info['desc'] || '');
                $('#loading').hide();
                $('li img').removeClass('highlightedThumb');
                $('#p_' + id).addClass('highlightedThumb');
                centerThumb();
                window.location.hash = id;
            }
            
            function centerThumb(){
                var left = ($('#func_bar').width() - 208) / 2 - $('#p_' + currentId).position().left;
                $('#func_bar ul').css('left', left + 'px');
            }
            
            function toggleNav(){
                $('#bottom_panel').toggle();
                $('#func_bar').toggle();
                if($('#func_bar').is(':visible')){
                    if(!thumb_loaded){
                        $('#thumb_container img').each(function(){
                            if($(this).attr('_src')){
                                $(this).attr('src', $(this).attr('_src'))
                                $(this).removeAttr('_src');
                            }
                        });
                        thumb_loaded = true;
                    }
                    centerThumb();
                }
                reposition();
            }
            
            function navPhoto(direction){   //-1: prev; 1:next
                if(direction == -1){
                    var index = $.inArray(currentId, ids) - 1;
                    if(index == -1){
                        index = ids.length - 1;
                    }
                    switchToPhoto(index);
                }else if(direction == 1){
                    var index = ($.inArray(currentId, ids) + 1) % ids.length;
                    switchToPhoto(index);
                }
            }
            function navPrevP(){navPhoto(-1);}
            function navNextP(){navPhoto(1);}
            
            
            $(document).ready(function() {
                $('ul').css('width', ids.length * 110 + 10 + 'px');
                //$('#num_of_photos').text(ids.length);
                    /*
                $('#nav').mouseenter(function(e){
                    $('#nav').css('background-image', 'none').animate({'height': '120px', 'width': '100%'}, 100, function(){
                        $('#func_bar').show();
                        centerThumb();
                    });
                    //第一次展现时才读取缩略图
                    $('li img').each(function(){
                        if($(this).attr('_src')){
                            $(this).attr('src', $(this).attr('_src'))
                            $(this).removeAttr('_src');
                        }
                    });
                }).mouseleave(function(){
                    $('#nav').animate({'height': '50px', 'width': '50px'}, 100, function(){
                        $('#func_bar').hide();
                        $('#nav').css('background-image', '/assets/sign.png');
                    });
                });*/
                /*
                $('#nav').mouseenter(function(){
                    if($('ul').is(":visible")){
                    }else{
                    }
                });
                */
                $('#nav_button').click(toggleNav);
                $('#nav_close').click(toggleNav);
                $('#nav_prev_p').click(navPrevP);
                $('#nav_next_p').click(navNextP);
                $(window).keydown(function(e){
                    if(currentId){
                        if(e.which == 34 || e.which == 37){ //左或向下翻页
                            navPhoto(-1);
                        }else if(e.which == 33 || e.which == 39){   //右或向上翻页
                            navPhoto(1);
                        }
                    }
                });
            	$('#func_bar li a').click(function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    var id = this.href.substr(this.href.indexOf('#') + 1)
                    _debug('thumb clicked: ' + id);
                    switchToPhoto($.inArray(id, ids));
                });
                var id = window.location.hash.substr(1);
                switchToPhoto($.inArray(id, ids));
                $("body").data("shouldPreload", true);
                $("body").data("allPreloaded", false);
                
                $(window).resize(function(){
                    reposition();
                });
            });
        </script>
    </head>
    <body>
        <div id="loading"><img src="/assets/loading.gif" alt="Loading..." /></div>
        <div id="index_tip"><span id="current_index"></span>/<span id="num_of_photos"></span></div>
        <div id="desc"></div>
        <img id="main_photo" src="" alt="" />
        <div id="func_bar">
            <div id="toolbar">
                <a href="javascript:void(0);" id="nav_close"></a>
                <a href="/album/${album.name}" id="nav_back"></a>
            </div>
            <div id="thumb_container">
                <ul>
                %for sib in album.photo_set.order('name'):
                    <li><a href="/photo/${album.name}#${sib.key().id()}">
                        <img id="p_${sib.key().id()}" _src="${sib.genThumbURL(104)}" alt="${sib.name}" />
                    </a></li>
                %endfor
                </ul>
            </div>
        </div>
        <div id="bottom_panel">
            <a href="/album/${album.name}" id="nav_back_2"></a>
            <div id="footer_left"></div>
            <div id="nav_zone">
                <a href="javascript:void(0);" id="nav_prev_p"></a>
                <a href="javascript:void(0);" id="nav_button"></a>
                <a href="javascript:void(0);" id="nav_next_p"></a>
            </div>
            <div id="footer_right"></div>
        </div>
    </body>
</html>